package com.ewhl.mark.meijialian;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.ewhl.mark.meijialian.jsbridge.BridgeHandler;
import com.ewhl.mark.meijialian.jsbridge.BridgeWebView;
import com.ewhl.mark.meijialian.jsbridge.CallBackFunction;
import com.ewhl.mark.meijialian.jsbridge.DefaultHandler;
import com.google.gson.Gson;



import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.widget.Toast.LENGTH_SHORT;


public class MainActivity extends Activity implements View.OnClickListener {

            private final String TAG = "MainActivity";

            BridgeWebView webView;

            Button button;

            int RESULT_CODE = 0;

            ValueCallback<Uri> mUploadMessage;

            static class Location {
                String address;
            }

            static class User {
                String name;
                Location location;
                String testStr;
            }

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                webView = (BridgeWebView) findViewById(R.id.web_content);

//                button = (Button) findViewById(R.id.button);
//
//                button.setOnClickListener(this);


                WebSettings webSettings = webView.getSettings();

//webview

                webSettings.setJavaScriptEnabled(true);

//启用数据库

                webSettings.setDatabaseEnabled(true);

//设置定位的数据库路径

                String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();

                webSettings.setGeolocationDatabasePath(dir);

//启用地理定位

                webSettings.setGeolocationEnabled(true);

//开启DomStorage缓存

                webSettings.setDomStorageEnabled(true);

                webView.setWebChromeClient(new WebChromeClient() {

                    @Override
                    public void onReceivedIcon(WebView view, Bitmap icon) {

                        super.onReceivedIcon(view, icon);

                    }

                    @Override
                    public void onGeolocationPermissionsShowPrompt(String origin,GeolocationPermissions.Callback callback) {

                        callback.invoke(origin, true, false);

                        super.onGeolocationPermissionsShowPrompt(origin, callback);

                    }

                });
                webView.setDefaultHandler(new DefaultHandler());

                webView.setWebChromeClient(new WebChromeClient() {

                    @SuppressWarnings("unused")
                    public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                        this.openFileChooser(uploadMsg);
                    }

                    @SuppressWarnings("unused")
                    public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                        this.openFileChooser(uploadMsg);
                    }

                    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                        mUploadMessage = uploadMsg;
                        pickFile();
                    }
                });
                //加载本地网页

                //webView.loadUrl("file:///android_asset/demo.html");
                //加载服务器网页
                webView.loadUrl("http://shejiao.cnewhl.com/index.php/mobile/NearbyGroup/group_dongtai_show/id/2296/key/1690a15684241b2a67444dd28a4d05f0");

                //必须和js同名函数，注册具体执行函数，类似java实现类。
                webView.registerHandler("submitFromWeb", new BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {

                        String str ="这是html返回给java的数据:" + data;
                        // 例如你可以对原始数据进行处理
                          Toast.makeText(MainActivity.this, str, LENGTH_SHORT).show();

                        Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
                        function.onCallBack( str + ",Java经过处理后截取了一部分："+ str.substring(0,5));
                    }

                });
                //模拟用户获取本地位置
                User user = new User();
                Location location = new Location();
                location.address = "上海";
                user.location = location;
                user.name = "Bruce";

                webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {
                        Toast.makeText(MainActivity.this, "网页在获取你的位置", LENGTH_SHORT).show();

                    }
                });

                webView.send("hello");

            }

            public void pickFile() {
                Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
                chooserIntent.setType("image/*");
                startActivityForResult(chooserIntent, RESULT_CODE);
            }

            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
                if (requestCode == RESULT_CODE) {
                    if (null == mUploadMessage){
                        return;
                    }
                    Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }

            @Override
            public void onClick(View v) {
                if (button.equals(v)) {
                    webView.callHandler("functionInJs", "data from Java", new CallBackFunction() {

                        @Override
                        public void onCallBack(String data) {
                            // TODO Auto-generated method stub
                            Log.i(TAG, "reponse data from js " + data);
                        }

                    });
                }

            }

        }
